//
//  GWMusicViewController.m
//  Glowalker
//
//  Created by 王华磊 on 2017/10/3.
//  Copyright © 2017年 Haley. All rights reserved.
//

#import <MediaPlayer/MediaPlayer.h>

#import "GWMusicViewController.h"
#import "GWMicphoneViewController.h"

#import "GWRhythmView.h"
#import "GWMusicListView.h"

#import "AVaudioplayerManager.h"
#import "RGBManager.h"
#import "MusicManager.h"
#import "ProgressHUD.h"

@interface GWMusicViewController ()<AVAudioPlayerDelegate>

@property (strong, nonatomic) UILabel       *songNameLabel;
@property (strong, nonatomic) UIImageView   *discImageView;
@property (strong, nonatomic) UIImageView   *coverImageView;

@property (weak, nonatomic) IBOutlet UIView *bottomView;
@property (weak, nonatomic) IBOutlet UILabel *playedTime;
@property (weak, nonatomic) IBOutlet UILabel *totalTime;
@property (weak, nonatomic) IBOutlet UISlider *slider;
@property (weak, nonatomic) IBOutlet UIButton *playListBtn;
@property (weak, nonatomic) IBOutlet UIButton *preBtn;
@property (weak, nonatomic) IBOutlet UIButton *playBtn;
@property (weak, nonatomic) IBOutlet UIButton *pauseBtn;
@property (weak, nonatomic) IBOutlet UIButton *nextBtn;
@property (weak, nonatomic) IBOutlet UIButton *mscSetBtn;

@property (strong, nonatomic) NSTimer        *currentTimeTimer;
@property (strong, nonatomic)   Song         *currentSong;

@property (assign, nonatomic)   BOOL         isRhythm;

@end

@implementation GWMusicViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self setupLanguage];
    
    NSUserDefaults *userdefaults = [NSUserDefaults standardUserDefaults];
    self.isRhythm = [userdefaults boolForKey:kRhythmMode];

    [self initNavigationBar];

    [self initMusicView];

    [self initToolView];

    [self initAudioSetting];
    
    BOOL flag = [[NSUserDefaults standardUserDefaults] boolForKey:kShowedFirstLanguage];
    if (!flag) {
        [self showChoseLanguageView];
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:kShowedFirstLanguage];
    }
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    BOOL rhythmMode = [[NSUserDefaults standardUserDefaults] boolForKey:kRhythmMode];
    BOOL isPlaying = [AVaudioplayerManager standardManager].player.isPlaying;
    if (isPlaying && rhythmMode) {
        [RGBManager start];
    }
}
    
- (void)setupLanguage
{
    self.navigationItem.title = showText(@"音乐");
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];

    BOOL rhythmMode = [[NSUserDefaults standardUserDefaults] boolForKey:kRhythmMode];
    BOOL isPlaying = [AVaudioplayerManager standardManager].player.isPlaying;
    if (isPlaying && rhythmMode) {
        [RGBManager stop];
    }
}

- (void)initAudioSetting
{
    [self writeFileWithName:@"1"];
    [self writeFileWithName:@"2"];
    [self writeFileWithName:@"3"];
    
    MusicManager *musicManager = [MusicManager share];
    [musicManager loadMusic];
    Song *song = [musicManager.songs firstObject];
    self.songNameLabel.text = song.songTitle;
    self.currentSong = song;
    [[AVaudioplayerManager standardManager] setupWithSong:song delegate:self Block:^(NSError *error) {
        if (error) {
            [ProgressHUD showError:showText(@"歌曲初始化失败")];
        } else {
            self.playedTime.text = [self strWithTime:0];
            self.totalTime.text = [self strWithTime:song.sumTime];
        }
    }];
}

- (void)initNavigationBar
{
    UIImage *rightImage = [UIImage imageNamed:@"music_microphone"];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:rightImage style:UIBarButtonItemStylePlain target:self action:@selector(rightClick)];
}

- (void)initMusicView
{
    UILabel *songNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, kWidth, 50)];
    songNameLabel.text = showText(@"歌名");
    songNameLabel.textColor = [UIColor whiteColor];
    songNameLabel.textAlignment = NSTextAlignmentCenter;
    songNameLabel.font = [UIFont boldSystemFontOfSize:22.0];
    [self.view addSubview:songNameLabel];
    self.songNameLabel = songNameLabel;
    
    CGFloat remainH = kHeight - 64-49-110-50;
    CGFloat discW = kWidth * 2/3;
    
    if (remainH < discW) {
        discW = remainH;
    }
    
    UIImageView *discImageView = [[UIImageView alloc] initWithFrame:CGRectMake((kWidth-discW) *0.5, 50, discW, discW)];
    discImageView.image = [UIImage imageNamed:@"ic_music_disc"];
    [self.view addSubview:discImageView];
    self.discImageView = discImageView;
    
    CGFloat coverW = discW * 0.54;
    UIImageView *coverImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, coverW, coverW)];
    coverImageView.center = CGPointMake(discW*0.5, discW*0.5);
    coverImageView.image = [UIImage imageNamed:@"music_logo"];
    coverImageView.layer.cornerRadius = coverW * 0.5;
    coverImageView.layer.masksToBounds = YES;
    [discImageView addSubview:coverImageView];
    self.coverImageView = coverImageView;
    
//    CGFloat needleW = discW * 0.4;
//    CGFloat needleH = needleW * 1.16;
//    UIImageView *needleImageView = [[UIImageView alloc] initWithFrame:CGRectMake(16, 16, needleW, needleH)];
//    needleImageView.image = [UIImage imageNamed:@"ic_music_magnet_needle"];
//    [self.view addSubview:needleImageView];
}

- (void)initToolView
{
    CGFloat bottomH = 110;
    self.bottomView.frame = CGRectMake(0, kHeight-64-49-bottomH, kWidth, bottomH);
    self.bottomView.backgroundColor = [UIColor clearColor];
    
    self.playedTime.frame = CGRectMake(8, 8, 42, 30);
    
    self.slider.frame = CGRectMake(16 + 42, 8, kWidth - (16+42)*2, 30);
    [self.slider addTarget:self action:@selector(sliderChange:) forControlEvents:UIControlEventValueChanged];
    
    self.totalTime.frame = CGRectMake(kWidth - 50, 8, 42, 30);
    
    CGFloat btnW = 44;
    CGFloat btnY = 46;
    CGFloat padding = (kWidth - 5*btnW)/6;
    
    self.playListBtn.frame = CGRectMake(padding, btnY, btnW, btnW);
    self.playListBtn.backgroundColor = [UIColor clearColor];
    [self.playListBtn addTarget:self action:@selector(playListClick) forControlEvents:UIControlEventTouchUpInside];
    [self.playListBtn setImage:[UIImage imageNamed:@"ic_music_playlist"] forState:UIControlStateNormal];
    
    self.preBtn.frame = CGRectMake(padding + btnW + padding, btnY, btnW, btnW);
    self.preBtn.backgroundColor = [UIColor clearColor];
    [self.preBtn addTarget:self action:@selector(preClick) forControlEvents:UIControlEventTouchUpInside];
    [self.preBtn setBackgroundImage:[UIImage imageNamed:@"ic_music_pre"] forState:UIControlStateNormal];
    
    self.pauseBtn.frame = CGRectMake(padding + (btnW + padding)*2, btnY, btnW, btnW);
    self.pauseBtn.backgroundColor = [UIColor clearColor];
    self.pauseBtn.hidden = YES;
    [self.pauseBtn addTarget:self action:@selector(pauseClick) forControlEvents:UIControlEventTouchUpInside];
    [self.pauseBtn setBackgroundImage:[UIImage imageNamed:@"ic_music_pause"] forState:UIControlStateNormal];
    
    self.playBtn.frame = CGRectMake(padding + (btnW + padding)*2, btnY, btnW, btnW);
    self.playBtn.backgroundColor = [UIColor clearColor];
    [self.playBtn addTarget:self action:@selector(playClick) forControlEvents:UIControlEventTouchUpInside];
    [self.playBtn setBackgroundImage:[UIImage imageNamed:@"ic_music_start"] forState:UIControlStateNormal];
    
    self.nextBtn.frame = CGRectMake(padding + (btnW + padding)*3, btnY, btnW, btnW);
    self.nextBtn.backgroundColor = [UIColor clearColor];
    [self.nextBtn addTarget:self action:@selector(nextClick) forControlEvents:UIControlEventTouchUpInside];
    [self.nextBtn setBackgroundImage:[UIImage imageNamed:@"ic_music_next"] forState:UIControlStateNormal];
    
    self.mscSetBtn.frame = CGRectMake(padding + (btnW + padding)*4, btnY, btnW, btnW);
    self.mscSetBtn.backgroundColor = [UIColor clearColor];
    [self.mscSetBtn addTarget:self action:@selector(mscSetClick) forControlEvents:UIControlEventTouchUpInside];
    [self.mscSetBtn setImage:[UIImage imageNamed:@"ic_music_setting"] forState:UIControlStateNormal];
}

#pragma mark - private method
- (void)writeFileWithName:(NSString *)name {
    //此处首先指定了图片存取路径（默认写到应用程序沙盒 中）
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    
    //并给文件起个文件名
    NSString *uniquePath=[[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.mp3",name]];
    BOOL blHave=[[NSFileManager defaultManager] fileExistsAtPath:uniquePath];
    if (blHave) {
        NSLog(@"already have");
        return ;
    }
    //此处的方法是将图片写到Documents文件中 如果写入成功会弹出一个警告框,提示图片保存成功
    NSString *strPathOld = [[NSBundle mainBundle] pathForResource:name ofType:@"mp3"];
    NSData *data = [NSData dataWithContentsOfFile:strPathOld];
    BOOL result = [data writeToFile:uniquePath atomically:YES];
    if (result) {
        NSLog(@"success");
    }else {
        NSLog(@"no success");
    }
}

- (NSString *)strWithTime:(NSTimeInterval)time
{
    int minute = time / 60;
    int second = (int)time % 60;
    
    NSString *str = [NSString stringWithFormat:@"%02d:%02d",minute, second];
    
    return str;
}

//添加旋转动画
- (void)addRotationAnimation
{
    CABasicAnimation *rotationA = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    rotationA.fromValue = 0;
    rotationA.toValue = @(M_PI * 2);
    rotationA.repeatCount = MAXFLOAT;
    rotationA.duration = 10.0f;
    rotationA.removedOnCompletion = NO;
    rotationA.fillMode = kCAFillModeForwards;
    [self.discImageView.layer addAnimation:rotationA forKey:@"rotation"];
    
    [self addCurrentTimeTimer];
}

- (void)removeRotationAnimation
{
    [self.discImageView.layer removeAnimationForKey:@"rotation"];
    
    [self removeCurrentTimeTimer];
}

- (void)updateLockedScreenMusic
{
    // 播放中心
    MPNowPlayingInfoCenter *center = [MPNowPlayingInfoCenter defaultCenter];
    
    // 组装播放信息字典
    NSMutableDictionary *infoDict = [NSMutableDictionary dictionary];
    infoDict[MPMediaItemPropertyTitle] = self.currentSong.songTitle;
    infoDict[MPMediaItemPropertyArtist] = self.currentSong.songArtist;
    infoDict[MPMediaItemPropertyAlbumTitle] = self.currentSong.songAlbum;
    infoDict[MPMediaItemPropertyArtwork] = [[MPMediaItemArtwork alloc] initWithImage:self.currentSong.songImage];
    AVAudioPlayer *player = [AVaudioplayerManager standardManager].player;
    infoDict[MPMediaItemPropertyPlaybackDuration] = @(player.duration);
    infoDict[MPMediaItemPropertyPlayCount] = @(player.currentTime);
    // 设置播放信息
    center.nowPlayingInfo = infoDict;
    
    //监听远程控制事件
    [self becomeFirstResponder];
    
    //开始监控
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
}

#pragma mark - 远程控制事件监听
- (BOOL)canBecomeFirstResponder
{
    return YES;
}

- (void)remoteControlReceivedWithEvent:(UIEvent *)event
{
    //    UIEventSubtypeRemoteControlPlay                 = 100,
    //    UIEventSubtypeRemoteControlPause                = 101,
    //    UIEventSubtypeRemoteControlStop                 = 102,
    //    UIEventSubtypeRemoteControlTogglePlayPause      = 103,
    //    UIEventSubtypeRemoteControlNextTrack            = 104,
    //    UIEventSubtypeRemoteControlPreviousTrack        = 105,
    //    UIEventSubtypeRemoteControlBeginSeekingBackward = 106,
    //    UIEventSubtypeRemoteControlEndSeekingBackward   = 107,
    //    UIEventSubtypeRemoteControlBeginSeekingForward  = 108,
    //    UIEventSubtypeRemoteControlEndSeekingForward    = 109,
    
    switch (event.subtype) {
        case UIEventSubtypeRemoteControlPlay:
            [self playClick];
            break;
        case UIEventSubtypeRemoteControlPause:
            [self pauseClick];
            break;
        case UIEventSubtypeRemoteControlNextTrack:
            [self nextClick];
            break;
        case UIEventSubtypeRemoteControlPreviousTrack:
            [self preClick];
            break;
        default:
            break;
    }
}

#pragma mark - 定时器处理
- (void)addCurrentTimeTimer
{
    AVAudioPlayer *player = [AVaudioplayerManager standardManager].player;
    if (!player.isPlaying) {
        return;
    }
    
    [self updateCurrentTime];
    
    self.currentTimeTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateCurrentTime) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:self.currentTimeTimer forMode:NSRunLoopCommonModes];
}

- (void)removeCurrentTimeTimer
{
    [self.currentTimeTimer invalidate];
    self.currentTimeTimer = nil;
}

// 更新
- (void)updateCurrentTime
{
    AVAudioPlayer *player = [AVaudioplayerManager standardManager].player;
    double progress = player.currentTime / player.duration;
    
    self.slider.value = progress;
    
    self.playedTime.text = [self strWithTime:player.currentTime];
}

#pragma mark - btn click events
- (void)rightClick
{
    GWMicphoneViewController *micphoneVC = [[GWMicphoneViewController alloc] init];
    micphoneVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:micphoneVC animated:YES];
}

- (void)preClick
{
    NSInteger previousIndex = 0;
    NSInteger index = [[MusicManager share].songs indexOfObject:self.currentSong];
    previousIndex = index - 1;
    if (previousIndex < 0) {
        previousIndex = [MusicManager share].songs.count - 1;
    }
    
    Song *song = [[MusicManager share].songs objectAtIndex:previousIndex];
    [[AVaudioplayerManager standardManager] setupWithSong:song delegate:self Block:^(NSError *error) {
        if (!error) {
            self.currentSong = song;
            self.songNameLabel.text = song.songTitle;
            self.playedTime.text = [self strWithTime:0];
            self.totalTime.text = [self strWithTime:song.sumTime];
            [self playClick];
        }
    }];
}

- (void)nextClick
{
    NSInteger nextIndex = 0;
    NSInteger index = [[MusicManager share].songs indexOfObject:self.currentSong];
    nextIndex = index + 1;
    if (nextIndex >= [MusicManager share].songs.count) {
        nextIndex = 0;
    }
    Song *song = [[MusicManager share].songs objectAtIndex:nextIndex];
    [[AVaudioplayerManager standardManager] setupWithSong:song delegate:self Block:^(NSError *error) {
        if (!error) {
            self.currentSong = song;
            self.songNameLabel.text = song.songTitle;
            self.playedTime.text = [self strWithTime:0];
            self.totalTime.text = [self strWithTime:song.sumTime];
            [self playClick];
        }
    }];
}

- (void)playClick
{
    [[AVaudioplayerManager standardManager] playMusic];
    [self addRotationAnimation];
    self.playBtn.hidden = YES;
    self.pauseBtn.hidden = NO;
}

- (void)pauseClick
{
    [[AVaudioplayerManager standardManager] pausePlay];
    [self removeRotationAnimation];
    self.playBtn.hidden = NO;
    self.pauseBtn.hidden = YES;
}

- (void)playListClick
{
    __weak typeof(self) weakSelf = self;
    GWMusicListView *musicListView = [[GWMusicListView alloc] initWithBlock:^(Song *song) {
        weakSelf.songNameLabel.text = song.songTitle;
        weakSelf.currentSong = song;
        [[AVaudioplayerManager standardManager] setupWithSong:song delegate:self Block:^(NSError * error) {
            if (error) {
                [ProgressHUD showError:showText(@"歌曲播放失败")];
            } else {
                self.playedTime.text = [self strWithTime:0];
                self.totalTime.text = [self strWithTime:song.sumTime];
                [self playClick];
            }
        }];
    }];
    [musicListView show];
}

- (void)mscSetClick
{
    __weak typeof(self) weakSelf = self;
    GWRhythmView *rhythmView = [[GWRhythmView alloc] initWithBlock:^(UISwitch *sender) {
        weakSelf.isRhythm = sender.on;
        [[NSUserDefaults standardUserDefaults] setBool:sender.on forKey:kRhythmMode];
        BOOL isPlaying = [AVaudioplayerManager standardManager].player.isPlaying;
        if (isPlaying) {
            if (sender.on) {
                [RGBManager start];
            } else {
                [RGBManager stop];
            }
        }
    }];
    [rhythmView show];
}

- (void)sliderChange:(UISlider *)slider
{
    float value = slider.value;
    NSTimeInterval total = [AVaudioplayerManager standardManager].player.duration;
    NSTimeInterval currentTime = total *value;
    [AVaudioplayerManager standardManager].player.currentTime = currentTime;
    
    self.playedTime.text = [self strWithTime:currentTime];
}

#pragma mark - AVAudioPlayerDelegate
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
    if (flag) {
        [self nextClick];
    }
}

@end
